package handler

import (
	"New-lesson-part2/custom_error"
	"New-lesson-part2/internal"
	"New-lesson-part2/proto/pb"
	"New-lesson-part2/shopcart_web/req"
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

// ShopCartListHandler 当前用户购物车列表
func ShopCartListHandler(c *gin.Context) {
	accountIdStr := c.Param("accountId")
	accountId, err := strconv.Atoi(accountIdStr)
	if err != nil {
		zap.S().Error("参数错误", err.Error())
	}
	res, err := internal.ShopCartClient.ShopCartItemList(context.Background(), &pb.AccountReq{AccountId: int32(accountId)})
	if err != nil {
		zap.S().Error("获取购物车列表错误", err.Error())
	}

	if err != nil {
		zap.S().Error("列表解析错误", err.Error())
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":   "cart-OK",
		"total": res.Total,
		"data":  res.ItemList,
	})
}

// AddHandler 添加购物车信息
func AddHandler(c *gin.Context) {
	var shopCardReq req.ShopCartReq
	err := c.ShouldBindJSON(&shopCardReq)
	zap.S().Error(shopCardReq)
	if err != nil {
		zap.S().Error(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": custom_error.ParameterError,
		})
		return
	}
	req2pb := ConvertShopCartReq2Pb(shopCardReq)
	shopCart, err := internal.ShopCartClient.AddShopCartItem(context.Background(), req2pb)
	if err != nil {
		zap.S().Error(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": custom_error.CreateShopCartFailed,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":          "",
		"shopCartItem": shopCart,
	})

}

// UpdateHandler 更新购物车信息
func UpdateHandler(c *gin.Context) {
	var productReq req.ShopCartReq
	err := c.ShouldBindJSON(&productReq)
	if err != nil {
		zap.S().Error(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": custom_error.ParameterError,
		})
		return
	}
	req2pb := ConvertShopCartReq2Pb(productReq)
	_, err = internal.ShopCartClient.UpdateShopCartItem(context.Background(), req2pb)
	if err != nil {
		zap.S().Error(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": err,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "",
	})
}

// DelHandler 删除
func DelHandler(c *gin.Context) {
	accountIdStr := c.Param("accountId")
	accountId, err := strconv.Atoi(accountIdStr)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": custom_error.ParameterError,
		})
		return
	}
	productIdStr := c.Param("accountId")
	productId, err := strconv.Atoi(productIdStr)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": custom_error.ParameterError,
		})
		return
	}
	_, err = internal.ShopCartClient.DeleteShopCartItem(context.Background(), &pb.DeleteShopCartReq{
		AccountId: int32(accountId),
		ProductId: int32(productId),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": custom_error.DeleteShopCartFailed,
		})
		return
	}

}

func ConvertShopCartReq2Pb(cart req.ShopCartReq) *pb.ShopCartReq {
	return &pb.ShopCartReq{
		Id:        cart.ID,
		AccountId: cart.AccountId,
		ProductId: cart.ProductId,
		Num:       cart.Num,
		Checked:   cart.Checked,
	}
}
